const { Customer, Goods, Category } = require("../models");

module.exports = {
  // 创建客户（需登录，附带 owner_id 和 owner_openid）
  async createCustomer(ctx) {
    const ownerId = ctx.state.user.id;
    const data = ctx.request.body;
    console.log("ownerOpenid:", ctx.state.user, ctx.request.body);

    const customer = await Customer.create({
      owner_id: ownerId,
      ...data,
    });

    ctx.body = {
      code: "0",
      msg: "客户创建成功",
      data: customer,
    };
  },

  // 后台获取当前登录用户的客户列表（需 token）
  async getCustomers(ctx) {
    const ownerId = ctx.state.user.id;

    const page = parseInt(ctx.query.page) || 1;
    const limit = parseInt(ctx.query.limit) || 10;
    const offset = (page - 1) * limit;

    const result = await Customer.findAndCountAll({
      where: { owner_id: ownerId },
      limit,
      offset,
      order: [["createdAt", "DESC"]],
    });

    ctx.body = {
      code: "0",
      msg: "客户列表获取成功",
      data: {
        total: result.count,
        list: result.rows,
        page,
        limit,
      },
    };
  },

  // 小程序前台：根据客户openid获取客户信息（无需token）
  async getCustomerByOpenid(ctx) {
    const openid = ctx.params.openid;

    const customer = await Customer.findOne({
      where: { openid },
    });

    if (!customer) {
      ctx.throw(404, "客户不存在");
    }

    ctx.body = {
      code: "0",
      msg: "客户信息获取成功",
      data: customer,
    };
  },

  // 小程序前台：根据客户openid获取该客户可见商品（无需token）
  async getGoodsByCustomerOpenid(ctx) {
    console.log(ctx.params, "ctx.params");

    const openid = ctx.params.openid;
    // 先找到客户
    const customer = await Customer.findOne({
      where: { openid },
    });
    if (!customer) {
      ctx.throw(404, "客户不存在");
    }

    // 查询客户对应用户发布的商品
    const goods = await Goods.findAll({
      where: { user_id: customer.owner_id },
      include: [{ model: Category, as: "category" }],
    });

    ctx.body = {
      code: "0",
      msg: "客户可见商品列表",
      data: goods,
    };
  },

  // 获取单个客户（需登录）
  async getCustomerById(ctx) {
    const ownerId = ctx.state.user.id;
    const id = ctx.params.id;

    const customer = await Customer.findOne({
      where: { id, owner_id: ownerId },
    });

    if (!customer) {
      ctx.throw(404, "客户不存在");
    }

    ctx.body = {
      code: "0",
      msg: "获取成功",
      data: customer,
    };
  },

  // 更新客户（需登录）
  async updateCustomer(ctx) {
    const ownerId = ctx.state.user.id;
    const id = ctx.params.id;
    const data = ctx.request.body;

    const customer = await Customer.findOne({
      where: { id, owner_id: ownerId },
    });

    if (!customer) {
      ctx.throw(404, "客户不存在");
    }

    await customer.update(data);

    ctx.body = {
      code: "0",
      msg: "更新成功",
      data: customer,
    };
  },

  // 删除客户（需登录）
  async deleteCustomer(ctx) {
    const ownerId = ctx.state.user.id;
    const id = ctx.params.id;

    const customer = await Customer.findOne({
      where: { id, owner_id: ownerId },
    });

    if (!customer) {
      ctx.throw(404, "客户不存在");
    }

    await customer.destroy();

    ctx.body = {
      code: "0",
      msg: "删除成功",
    };
  },
};
